package cn.edu.niit.studyspace.fragment;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;

import org.javia.arity.Symbols;
import org.javia.arity.SyntaxException;

import cn.edu.niit.studyspace.R;

public class CalculatingFragment extends Fragment implements View.OnClickListener {

  TextView tvInput;
  boolean clrFlag = false; // 判断et编辑文本框中是否清空
  String str;

  @Nullable
  @Override
  public View onCreateView(
      @NonNull LayoutInflater inflater,
      @Nullable ViewGroup container,
      @Nullable Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_calculating, container, false);

    ((AppCompatActivity) getActivity()).getSupportActionBar().setTitle("计算器");
    str = "";
    clrFlag = false;
    tvInput = view.findViewById(R.id.tv_input);

    return view;
  }

  public void onClick(View view) {

    switch (view.getId()) {
      case R.id.btn_0:
      case R.id.btn_1:
      case R.id.btn_2:
      case R.id.btn_3:
      case R.id.btn_4:
      case R.id.btn_5:
      case R.id.btn_6:
      case R.id.btn_7:
      case R.id.btn_8:
      case R.id.btn_9:
      case R.id.btn_add:
      case R.id.btn_sub:
      case R.id.btn_mul:
      case R.id.btn_div:
      case R.id.btn_pt:
        str = tvInput.getText().toString();
        str += ((Button) view).getText().toString();
        tvInput.setText(str);
        break;
      case R.id.btn_clr:
        tvInput.setText(null);
        break;
      case R.id.btn_del:
        String myStr = tvInput.getText().toString();
        try {
          tvInput.setText(myStr.substring(0, myStr.length() - 1));
        } catch (Exception e) {
          tvInput.setText("");
        }

        break;
      case R.id.btn_eq:
        getResult();
        break;
    }
  }

  private void getResult() {
    clrFlag = true; // 当按下等号=，设为true
    str = tvInput.getText().toString();
    String reg = "^[0-9]+(.\\d+)?[+\\-×÷]\\d+(.\\d+)?";
    if (!str.isEmpty() && str.matches(reg)) {
      Symbols symbols = new Symbols();
      try {
        float result = (float) symbols.eval(str);
        tvInput.setText(result + "");
      } catch (SyntaxException e) {
        e.printStackTrace();
      }
    } else {
      Toast.makeText(getActivity(), str + "不是一个合法的表达式", Toast.LENGTH_LONG).show();
    }
  }
}
